package com.ahncnk.powermonitor.admin.auth.controller;

import com.ahncnk.powermonitor.admin.auth.domain.dto.Token;
import com.ahncnk.powermonitor.admin.auth.service.AuthService;
import com.ahncnk.powermonitor.admin.users.domain.entity.User;
import com.ahncnk.powermonitor.admin.users.service.UserService;
import com.ahncnk.powermonitor.commons.exception.ApplicationRuntimeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * AuthController
 *
 * @author lipei
 */
@RestController
public class AuthController {
    @Resource
    private UserService userService;
    @Resource
    private AuthService authService;
    @Value("${spring.application.name}")
    private String appName;

    @RequestMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpServletResponse response) {
        Optional<User> userOpt = userService.findByUsername(username);
        if (!userOpt.isPresent()) {
            throw new ApplicationRuntimeException(HttpStatus.FORBIDDEN, "用户名或密码错误", "找不到用户名为\"" + username + "\"的用户");
        }
        User user = userOpt.get();
        String inputPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!inputPassword.equals(user.getPassword())) {
            throw new ApplicationRuntimeException(HttpStatus.FORBIDDEN, "用户名或密码错误", "密码输入错误：" + password + "，md5后得到：" + inputPassword + "。期望值：" + user.getPassword());
        }
        Token token = authService.sign(user);
        response.addCookie(token.getPayload());
        response.addCookie(token.getSignature());
        return "OK";
    }
}
